﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;

namespace ESoft.RabbitMQ
{
    /// <summary>
    /// 服务扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注入rabbitMQ
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        public static void AddRabbitMQ(this IServiceCollection services, params Assembly[] assemblies)
        {
            Type baseType = typeof(IConsumer);

            Type[] mapperTypes = assemblies.SelectMany(assembly => assembly.GetTypes())
                .Where(type => baseType.IsAssignableFrom(type) && type != baseType && !type.IsAbstract).ToArray();

            foreach (Type type in mapperTypes)
            {
                services.AddSingleton(baseType, type);
            }
            services.AddSingleton<IRabbitFactory, RabbitFactory>();
            services.AddSingleton<IRabbitMQService, RabbitMQService>();
            services.AddSingleton<IChannelObjectPool, ChannelPool>();
        }

        /// <summary>
        /// 启动RabbitMQ消费者
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        public static void UseRabbitMQConsumer(this IServiceProvider services, params Assembly[] assemblies)
        {
            var consumers = services.GetServices<IConsumer>();
            if (consumers.Any())
            {
                IRabbitMQService rabbitMQService = services.GetRequiredService<IRabbitMQService>();
                rabbitMQService.StartConsumers(consumers, assemblies);
            }

        }
    }
}
